- Basic Operations
- Moving Data Around
- Computing on Data
- Plotting Data
- Control statements:
for
,while
,if
statements - Functions
- Vectorization
- Working on and Submitting Programming Exercises
Basic Operations
1 | %% Change Octave prompt |
Moving Data Around
Dimensions
1 | %% dimensions |
Loading data
1 | %% loading data |
Indexing
1 | %% indexing |
Computing on Data
Matrix operation
1 | %% initialize variables |
Useful functions
1 | %% misc useful functions |
Plotting Data
1 | %% plotting |
Control statements: for
, while
, if
statements
1 | v = zeros(10,1); |
Functions
To create a function, type the function code in a text editor (e.g. gedit or notepad), and save the file as "functionName.m
"
Example function: 1
2
3function y = squareThisNumber(x)
y = x^2;
To call the function in Octave, do either:
Navigate to the directory of the
functionName.m
file and call the function:1
2
3
4
5% Navigate to directory:
cd /path/to/function
% Call the function:
functionName(args)Add the directory of the function to the load path and save it:
1
2
3
4
5% To add the path for the current session of Octave:
addpath('/path/to/function/')
% To remember the path for future sessions of Octave, after executing addpath above, also do:
savepath
Octave's functions can return more than one value: 1
2
3function [y1, y2] = squareandCubeThisNo(x)
y1 = x^2
y2 = x^3
Call the above function this way: 1
[a,b] = squareandCubeThisNo(x)
Vectorization
Vectorization is the process of taking code that relies on loops and converting it into matrix operations. It is more efficient, more elegant, and more concise.
As an example, let's compute our prediction from a hypothesis. Theta is the vector of fields for the hypothesis and x is a vector of variables.
With loops: 1
2
3
4prediction = 0.0;
for j = 1:n+1,
prediction += theta(j) * x(j);
end;
With vectorization: 1
prediction = theta' * x;
If you recall the definition multiplying vectors, you'll see that this one operation does the element-wise multiplication and overall sum in a very concise notation.
Working on and Submitting Programming Exercises
- Download and extract the assignment's zip file.
- Edit the proper file 'a.m', where a is the name of the exercise you're working on.
- Run octave and cd to the assignment's extracted directory
- Run the 'submit' function and enter the assignment number, your email, and a password (found on the top of the "Programming Exercises" page on coursera)